<template>
  <div class="guide">
    <c-title :text="is_retail?'零售':'订货'"></c-title>
    <van-search
      class="search-goods-bar"
      v-model="searchGoodsKeyword"
      show-action
      placeholder="请输入搜索的内容"
      shape="round"
    >
      <template #action>
        <div class="explain-show-button" @click="showExplainPopup=!showExplainPopup">
          <i class="iconfont icon-dingdan1"></i>
          说明
        </div>
      </template>
    </van-search>
    <img :src="sets.banner" class="top-banner" v-show="sets.banner && !is_retail" />
    <d-list @load="getGoodsList" :loading="goodsLoading" :finished="goodsLoadFinished">
      <ul class="goods-list" @click="viewGoods($event)">
        <goods-item
          class="goods-item"
          v-for="(goodsItem,index) in goodsList"
          :isCart="isCart"
          :key="goodsItem.id"
          :data="goodsItem"
          :index = "index"
          :show_price="show_price"
          :show_price_flag="show_price_flag"
          @add="addCart"
          @show="showGoodDetail" @change="changeCart"
        />
      </ul>
    </d-list>
    <van-popup v-model="showExplainPopup" round closeable>
      <div class="explain-popup-content">
        <div class="explain-title">说明</div>
        <div class="explain-content" v-html="sets.summary"></div>
      </div>
    </van-popup>

  <div class="bottom-fixed-button set-pc-style" v-show="isCart">
    <div class="small-price">{{ $i18n.t("money") }}</div>
            {{ cartsTotal }}
      <div class="button" @click.stop="openCartListPopup">
        去结算<em class="carts-num">{{ cartsNum }}</em>
      </div>

    </div>
    <!-- 购物车列表弹窗 -->
    <yz-cart-list v-model="showCarList" :cardata="cartList" class="carlist" v-on:clearCart="clearCart" v-on:blur="changeCarList" v-on:plus="changeCarList" v-on:minus="changeCarList" :showDestory="true">
      <!-- 底部购物车 -->
      <div class="bottom-car set-pc-styleLeft">
        <div class="car-box">
          <div class="car-num" @click.stop="showCarList = false">
            <div class="car-num-box">
              <i class="iconfont icon-all_buycar"></i>
              <div class="carnum-style">{{ cartsNum }}</div>
            </div>
            <div class="small-price">{{ $i18n.t("money") }}</div>
            {{ cartsTotal }}
          </div>
          <div class="car-add" @click.stop="toOrder">去结算</div>
        </div>
      </div>
    </yz-cart-list>

    <!-- 商品详情页弹窗 -->
    <yzGoodsPopup v-model="showgp" :goodsInfo="goodinfo" v-on:showgoodspecs="showgoodspecs"></yzGoodsPopup>
    <!-- 商品规格弹窗 -->
    <yz-specs :goodsInfo="goodinfo" v-model="popupSpecs" v-on:closeSpecsPopup="close_yz_specs_popup"></yz-specs>
  </div>
</template>

<script>
import { Search, Popup, Toast } from "vant";
import GoodsItem from "../../../components/member/stock/goods_item.vue";
import yzGoodsPopup from "components/ui_components/yz_goodsPopup";
import yzSpecs from "components/ui_components/yz_specs";
import yzCartList from "components/ui_components/yz_cartList";
import DList from "@/components/dlist";
export default {
  data() {
    return {
      isCart: true,
      showExplainPopup: false,
      sets: {
        summary: "", //* 说明内容
        banner: "" //* 搜索栏下的海报图片
      },
      goods: [],
      goodsLoadPage: 1, //* 商品加载页数
      goodsLoading: false, //* 商品是否记载中
      goodsLoadFinished: false, //* 商品是否加载完成
      searchGoodsKeyword: "",
      is_retail:false,


      cartList: [],
      cartsNum: 0, //购物车数量
      activity_gid: 0,
      activity_index: 0,
      showgp: false,
      popupSpecs: false,
      goodinfo: {},
      showCarList: false,
      cartsTotal: 0,

      show_price:false,
      show_price_flag:false,
    };
  },
  activated() {
    this.getGoodsList();
    if(this.$route.params.target){
      this.is_retail = true;
      this.isCart = false;
    }
    this.show_price_flag =this.$route.path == '/stock/guide' ?true:false;
  },
  methods: {
    getGoodsList() {
      if (this.goodsLoading === true || this.goodsLoadFinished === true) {
        return;
      }
      this.goodsLoading = true;
      let json = {
        page: this.goodsLoadPage,
        is_retail : this.is_retail
      };
      $http
        .post("plugin.agency.api.goods.goods-list", json)
        .then(({ data, result, msg }) => {
          if (result === 0) {
            Toast(msg);
            return;
          }
          this.show_price = data.show_price;
          if (data.data.length === 0 || data.data.length < data.per_page || data.current_page === data.last_page) {
            this.goodsLoadFinished = true;
          }
          this.goodsLoadPage++;
          this.sets.banner = data.set.banner;
          this.sets.summary = data.set.summary;
          this.goods.push(...data.data);
          this.goodsLoading = false;
          this.getCartList();
        });
    },
    viewGoods({ target: { dataset } }) {
      const id = dataset.gid;
      if (!id) {
        return;
      }
      let json = {fromStock: 1};
      if(this.is_retail){
        json.is_retail = this.is_retail;
      }
      this.$router.push(
        this.fun.getUrl(
          "goods",
          {
            id
          },
          json
        )
      );
    },

    getCartList() {
      //获取购物车列表，该列表继承商城购物车，只返回通过接口postageIncludedCategory.member-cart.store添加的购物车数据
      $http
        .get("plugin.agency.api.member-cart.index", {has_retail :this.$route.params.target?1:0}, ".")
        .then(res => {
          if (res.result == 1) {
            this.cartList = res.data;
            this.setGoodTotal();
          } else {
            this.$toast(res.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    setGoodTotal() {
      this.cartsNum = 0;
      this.cartsTotal = 0;
      // 计算设置当前商品列表中是否有已加入购物车的数据，有则显示购物车数量
      for (let index = 0; index < this.cartList.length; index++) {
        this.cartsNum += this.cartList[index].total;
        for (let j = 0; j < this.goods.length; j++) {
          if (index == 0 && this.goods[j].total) {
            this.goods[j].total = 0; //初始化置0
          }
          if (this.cartList[index].goods_id == this.goods[j].id) {
            let _total = 0;
            if (this.cartList[index].option_id == 0) {
              // 无规格
              _total = this.cartList[index].total; //设置商品的购物车数量
              this.cartsTotal += this.cartList[index].total * this.cartList[index].goods.price;
            } else {
              // 有规格
              _total = this.goods[j].total || 0;
              _total += this.cartList[index].total;
              this.cartsTotal += this.cartList[index].total * this.cartList[index].goods_option.product_price;
            }
            this.$set(this.goods[j], "total", _total); //设置商品的购物车数量
            this.goods[j].card_id = this.cartList[index].id; //设置商品的购物车id
          }
        }
      }
    },
    addCart(e) {
      console.log(e);
      this.activity_index = e.index;
      if (e.isSpecs) {
        this.goodinfo = this.goodsList[e.index];
        this.activity_gid = e.id;
        this.popupSpecs = true; //规格商品，显示规格弹窗
        // this.showGoodDetail(e, true); //规格商品，显示规格弹窗
        return;
      }
      this.addMemberCart({ id: e.id, total: "1", index: e.index });
    },
    addMemberCart(_data) {
      //添加到购物车
      if (!_data.id) return;
      let _json = {
        goods_id: _data.id,
        total: _data.total || 1,
        option_id: _data.option_id || 0
      };
      $http
        .get("plugin.agency.api.member-cart.store", _json, ".")
        .then(res => {
          if (res.result == 1) {
            this.popupSpecs = false;
            this.showgp = false;
            this.$toast(res.msg);
            this.$set(this.goods[_data.index], "total", _data.total);
          } else {
            this.$toast(res.msg);
          }
          this.getCartList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    showGoodDetail(e, _spec) {
      return;
      if (this.activity_gid == e.id) {
        if (!_spec) {
          this.showgp = true;
        } else {
          this.popupSpecs = true;
        }
        return;
      }

      this.activity_gid = e.id;
      $http
        .get("goods.goods.get-goods-page", { id: Number(e.id) }, ".")
        .then(res => {
          if (res.result == 1) {
            this.goodinfo = res.data.get_goods;
            if (res.data.get_goods.content) {
              let str = this.goodinfo.content.replace(/src=\"http:/gi, 'src="https:');
              this.goodinfo.content = str;
            } else {
              this.goodinfo.content = "暂无该商品详情";
            }
            setTimeout(() => {
              if (!_spec) {
                this.showgp = true;
              } else {
                this.popupSpecs = true;
              }
            }, 200);
          } else {
            this.$toast(res.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    changeCart(e) {
      // 更新购物车数量
      console.log(e);
      if (!e.cartId) {
        return;
      }
      if (Number(e.num) == 0) {
        //删除购物车
        this.destroyCart(e.cartId);
        this.$set(this.goods[e.index], "total", 0);
        return;
      }
      $http
        .get("plugin.agency.api.member-cart.updateNumV2", { id: e.cartId, num: e.num }, ".")
        .then(res => {
          if (res.result == 1) {
            this.popupSpecs = false;
            this.showgp = false;
            if (e.index) this.$set(this.goods[e.index], "total", e.num);
          }
          this.$toast(res.msg);
          this.getCartList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    destroyCart(_id) {
      $http
        .get("plugin.agency.api.member-cart.destroy", { ids: _id }, ".")
        .then(res => {
          this.$toast(res.msg);
          this.getCartList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    openCartListPopup() {
      this.showCarList = true;
    },
    close_yz_specs_popup(_optionsId, goodsCount, clicktype, id) {
      console.log("规格弹窗关闭了=====", _optionsId, goodsCount, clicktype, id);
      this.popupSpecs = false;
      if (clicktype == 1) {
        //点击确认按钮
        this.addMemberCart({ id: this.activity_gid, total: goodsCount, option_id: _optionsId, index: this.activity_index });
      }
    },
    toOrder() {
      //当前是否是从下单页跳转过来的
      let _cart_ids = [];
      let _cartArr = [];

      this.cartList.forEach(item => {
        _cart_ids.push(item.id);
      });
      _cartArr = new Set(_cart_ids);
      _cartArr = [..._cartArr]; //去重

      this.$nextTick(() => {
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              tag: "-1",
              cart_ids: _cartArr.join(","),
              fromStock: 1
            }
          )
        );
      });
    },
    clearCart(){
      let destroyCarts = [];
      this.cartList.forEach(item => {
        destroyCarts.push(item.id);
      });
      $http
        .get("plugin.agency.api.member-cart.destroy", {
          ids: destroyCarts
        })
        .then(response => {
          if (response.result == 1) {
            this.goodsLoading = false;
            this.goodsLoadFinished = false;
            this.goods = [];
            this.goodsLoadPage = 1;
            this.getGoodsList();
            this.showCarList = false;
            this.cartsNum = 0;
            this.cartsTotal = 0;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        });
    },
    changeCarList(e) {
      let _total = e.name == "plus" ? e.total + 1 : e.name == "minus" ? e.total - 1 : e.total;
      this.changeCart({ cartId: e.id, num: _total });
    },
  },
  computed: {
    goodsList() {
      if (this.searchGoodsKeyword) {
        return this.goods.filter(item => {
          return item.title.indexOf(this.searchGoodsKeyword) !== -1;
        });
      } else {
        return this.goods;
      }
    }
  },
  components: {
    VanSearch: Search,
    VanPopup: Popup,
    GoodsItem,
    DList,
    yzCartList,
    yzGoodsPopup,
    yzSpecs
  }
};
</script>

<style lang="scss" rel="stylesheet/scss" scoped >
/* 搜索栏 */

/* .search-goods-bar { */

/* } */

.explain-show-button {
  padding-left: 1.0313rem;
  color: #f14e4e;
}

.van-search__action:active {
  background: none;
}

/* 说明弹窗 */
.explain-popup-content {
  padding: 1.75rem 1.3438rem;
  width: 16.875rem;
  height: 14.6875rem;
  background: white;
}

.explain-title {
  font-size: 1rem;
  font-weight: 500;
  color: #161615;
}

.explain-content {
  margin-top: 1.25rem;
  line-height: 1.1875rem;
  text-align: left;
  font-size: 0.75rem;
  color: #6e6e6e;
}

/* 置顶海报 */
.top-banner {
  width: 100%;
  height: 10.9375rem;
  object-fit: cover;
}

/* 商品列表 */
.goods-list {
  margin-top: 0.9375rem;
  padding: 0 0.9375rem 0.9375rem;
}

.goods-item {
  margin-bottom: 0.625rem;
}
.bottom-car {
  position: fixed;
  width: 100%;
  height: 4.5rem;
  left: 0;
  bottom: -1px;
  display: flex;
  align-items: center;
  background-image: linear-gradient(180deg, hsla(0, 0%, 100%, 0), #fff 19%);

  .car-box {
    border: 1px solid #f14e4e;
    border-radius: 1.5rem;
    display: flex;
    align-items: center;
    height: 3rem;
    line-height: 3rem;
    width: 90%;
    margin: 0 auto;
    overflow: hidden;

    .car-num-box {
      position: relative;
      width: 3rem;
      text-align: center;

      .carnum-style {
        position: absolute;
        height: 1rem;
        right: 0;
        top: 5px;
        line-height: 1rem;
        background: #f14e4e;
        border-radius: 1rem;
        color: #fff;
        padding: 0 0.25rem;
        font-size: 0.75rem;
      }
    }

    .car-num {
      min-width: 50%;
      text-align: left;
      color: #f14e4e;
      display: flex;
      padding-right: 10px;

      i {
        font-size: 1.5rem;
      }

      .small-price {
        font-size: 0.75rem;
      }

      font-size: 14px;
    }

    .car-add {
      flex: 1;
      text-align: center;
      background-color: #f14e4e;
      color: #fff;
    }
  }

  .endstyle {
    background: #d8d8d8;
    border-color: #d8d8d8;
    color: #fff;
    text-align: center;
    font-size: 1.25rem;
    display: block;
  }
}

.carlist {
  .bottom-car {
    position: relative;
  }
}
.bottom-fixed-button {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 3.125rem;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 1rem;
    z-index: 100;
    background-color: #fff;
    box-shadow: 1px 1px 14px 0 rgba(184, 184, 184, 0.52);

    .button {
      margin-left: 0.875rem;
      width: 90px;
      height: 32px;
      line-height: 32px;
      background-color: #f15053;
      border-radius: 16px;
      font-size: 14px;
      color: #fff;
      position: relative;
    }

    .carts-num {
      padding: 0 0.25rem;
      min-width: 1.25rem;
      height: 1.25rem;
      line-height: 1.25rem;
      font-size: 14px;
      position: absolute;
      top: -8px;
      right: -5px;
      background-color: #ff5d5c !important;
      color: #fff;
      border-radius: 0.875rem;
      box-shadow: 1px 1px 6px #b74444;
    }
  }
</style>